<template>
  <div class="sidebar-filter">
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-group">
        <div class="filter-label">排序方式</div>
        <el-select
          :model-value="sortBy"
          @update:model-value="onSortChange"
          placeholder="排序方式"
          size="large"
        >
          <el-option label="按名称排序" value="name" />
          <el-option label="按时间排序" value="time" />
          <el-option label="按大小排序" value="size" />
        </el-select>
      </div>
      <div class="filter-group">
        <div class="filter-label">文件类型</div>
        <div class="filter-list">
          <div
            v-for="type in fileTypes"
            :key="type.value"
            class="filter-item"
            :class="{ 'is-active': activeType === type.value }"
            @click="handleTypeClick(type.value)"
          >
            <el-icon><component :is="type.icon" /></el-icon>
            <span class="label">{{ type.label }}</span>
            <span class="count">{{ getTypeCount(type.value) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 分组区域 -->
    <div class="group-section">
      <div class="section-title">
        <span>分组</span>
        <el-button type="primary" text @click="onAddGroup">
          <el-icon><Plus /></el-icon>
          新建分组
        </el-button>
      </div>
      <div class="group-list">
        <div
          v-for="group in mediaGroups"
          :key="group.id"
          class="group-item"
          :class="{ 'is-active': activeGroup === group.id }"
          @click="handleGroupClick(group.id)"
        >
          <el-tooltip
            v-if="group.description"
            :content="group.description"
            placement="right"
            effect="light"
            :show-after="300"
          >
            <div class="group-info">
              <el-icon><Folder /></el-icon>
              <span class="name">{{ group.name }}</span>
              <el-icon v-if="group.description" class="info-icon"><InfoFilled /></el-icon>
            </div>
          </el-tooltip>
          <div class="group-info" v-else>
            <el-icon><Folder /></el-icon>
            <span class="name">{{ group.name }}</span>
          </div>
          <div class="group-actions">
            <span class="count">{{ getGroupCount(group.id) }}</span>
            <el-icon
              v-if="group.id !== -1 && group.id !== 1"
              class="edit-icon"
              @click.stop="onEditGroup(group)"
            >
              <Edit />
            </el-icon>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
/**
 * 左侧筛选栏组件
 *
 * 功能：
 * 1. 提供文件类型筛选
 * 2. 分组管理与切换
 * 3. 排序方式选择
 */
import { defineProps, defineEmits, ref, computed, onMounted, defineExpose, watchEffect } from 'vue'
import { Plus, Folder, Files, Picture, Document, InfoFilled, Edit } from '@element-plus/icons-vue'
import {
  getTypeCount as getTypeCountUtil,
  getGroupCount as getGroupCountUtil,
} from '@/utils/mediaUtils'
import { sourceApi } from '@/api/source'

/**
 * 组件接口定义
 */
interface FileType {
  value: string
  label: string
  icon: any
}

interface MediaGroup {
  id: number
  name: string
  description?: string
  fileNum?: number
}

interface MediaFile {
  id: number
  type: 'image' | 'document'
  groupId: number
  // 其他属性
}

/**
 * 组件属性
 */
const props = defineProps<{
  /** 当前选中的文件类型 */
  activeType: string
  /** 当前选中的分组ID */
  activeGroup: number | null
  /** 当前排序方式 */
  sortBy: 'time' | 'name' | 'size'
  /** 分组列表 */
  mediaGroups: MediaGroup[]
  /** 媒体文件列表 */
  mediaList: MediaFile[]
}>()

/**
 * 组件事件
 */
const emit = defineEmits<{
  /** 文件类型变更 */
  (e: 'typeChange', type: string): void
  /** 分组变更 */
  (e: 'groupChange', groupId: number | null): void
  /** 排序方式变更 */
  (e: 'sortChange', sort: 'time' | 'name' | 'size'): void
  /** 添加分组 */
  (e: 'addGroup'): void
  /** 编辑分组 */
  (e: 'editGroup', group: MediaGroup): void
}>()

/**
 * 文件类型配置
 */
const fileTypes: FileType[] = [
  { value: 'all', label: '全部文件', icon: Files },
  { value: '0', label: '图片', icon: Picture },
  { value: '1', label: '文档', icon: Document },
  { value: '2', label: '其他', icon: Files },
]

/**
 * 文件类型数量
 */
const typeCounts = ref({
  imageCount: 0,
  docCount: 0,
  otherCount: 0,
})

/**
 * 获取指定类型的文件数量
 * @param {string} type 文件类型
 * @returns {number} 文件数量
 */
const getTypeCount = (type: string): number => {
  // 确保typeCounts有值
  if (!typeCounts.value) return 0

  if (type === 'all') {
    return (
      (typeCounts.value.imageCount || 0) +
      (typeCounts.value.docCount || 0) +
      (typeCounts.value.otherCount || 0)
    )
  } else if (type === '0') {
    return typeCounts.value.imageCount || 0
  } else if (type === '1') {
    return typeCounts.value.docCount || 0
  } else if (type === '2') {
    return typeCounts.value.otherCount || 0
  }
  return 0
}

/**
 * 获取指定分组的文件数量
 * @param {number} groupId 分组ID
 * @returns {number} 文件数量
 */
const getGroupCount = (groupId: number): number => {
  // 查找对应分组
  const group = props.mediaGroups.find((g) => g.id === groupId)

  // 如果找到分组且有fileNum字段，直接使用后端提供的数量
  if (group && group.fileNum !== undefined) {
    // 返回后端提供的文件数量
    return group.fileNum
  }

  // 如果是未分组且未找到组或无fileNum值，则使用API总数和已分组文件数计算
  if (groupId === -1) {
    // 获取API提供的可能的总数
    const apiTotalCount =
      typeCounts.value.imageCount + typeCounts.value.docCount + typeCounts.value.otherCount

    // 计算其他所有分组的文件总数
    let totalGroupedFiles = 0

    // 仅计算有固定fileNum的分组，避免计算不准确
    props.mediaGroups.forEach((g) => {
      console.log(g)
      if (g.id !== -1 && g.fileNum !== undefined) {
        totalGroupedFiles += g.fileNum
      }
    })

    // 如果有可靠的API总数，则用API总数减去已分组数量
    if (apiTotalCount > 0) {
      const ungroupedCount = Math.max(0, apiTotalCount - totalGroupedFiles)
      console.log('[未分组文件计算]', {
        apiTotalCount,
        totalGroupedFiles,
        ungroupedCount,
      })
      return ungroupedCount
    }
  }

  // 最后的降级方案：手动计算文件数量
  const manualCount = getGroupCountUtil(props.mediaList, groupId)
  console.log('[手动计算文件数量]', { groupId, count: manualCount })
  return manualCount
}

/**
 * 处理文件类型点击事件
 */
const handleTypeClick = (type: string) => {
  emit('typeChange', type)
}

/**
 * 处理分组点击事件
 */
const handleGroupClick = (groupId: number) => {
  emit('groupChange', groupId === props.activeGroup ? null : groupId)
}

/**
 * 处理排序变更事件
 */
const onSortChange = (value: 'time' | 'name' | 'size') => {
  emit('sortChange', value)
}

/**
 * 处理添加分组事件
 */
const onAddGroup = () => {
  emit('addGroup')
}

/**
 * 处理编辑分组事件
 */
const onEditGroup = (group: MediaGroup) => {
  emit('editGroup', group)
}

/**
 * 加载文件类型数量
 */
const loadTypeCounts = async () => {
  try {
    const res = await sourceApi.getSourceCount()
    if (res) {
      typeCounts.value = {
        imageCount: res.imageCount || 0,
        docCount: res.docCount || 0,
        otherCount: res.otherCount || 0,
      }
    }
  } catch (error) {
    console.error('加载文件类型数量失败:', error)
    // 设置默认值，确保UI不会崩溃
    typeCounts.value = {
      imageCount: 0,
      docCount: 0,
      otherCount: 0,
    }
  }
}

/**
 * 组件挂载时加载数据
 */
onMounted(() => {
  loadTypeCounts()
})

/**
 * 监听媒体文件和分组数据变化，确保未分组数量准确
 */
watchEffect(() => {
  // 当mediaList或mediaGroups变化时，这个函数会自动执行
  // 不需要做其他操作，因为getGroupCount已经会根据最新数据计算
  // 这里存在是为了触发组件重新渲染，从而更新显示的数量
  props.mediaList.length
  props.mediaGroups.length
})

/**
 * 暴露方法给父组件
 */
defineExpose({
  loadTypeCounts,
})
</script>

<style lang="scss" scoped>
// 导入主题变量和混合器
@use '@/assets/styles/theme/base.scss' as *;
@use '@/assets/styles/mixins.scss' as *;

/**
 * 左侧筛选栏样式
 */
.sidebar-filter {
  width: 100%;
  height: 100%;

  /**
   * 分组标题
   */
  .section-title {
    @include flex-between;
    margin-bottom: 16px;

    span {
      font-size: $font-size-body;
      font-weight: 500;
      color: $text-primary;
    }
  }

  /**
   * 筛选区域
   */
  .filter-section {
    margin-bottom: 24px;

    .filter-group {
      & + .filter-group {
        margin-top: 16px;
      }

      .filter-label {
        font-size: $font-size-small;
        color: $text-secondary;
        margin-bottom: 8px;
      }

      .el-select {
        width: 100%;
      }

      .filter-list {
        display: flex;
        flex-direction: column;
        gap: 4px;

        /**
         * 筛选项
         */
        .filter-item {
          padding: 8px 12px;
          border-radius: $radius-medium;
          cursor: pointer;
          @include transition(all);
          @include flex-between;

          .el-icon {
            font-size: 16px;
            margin-right: 8px;
            @include transition(all);
          }

          .label {
            flex: 1;
            font-size: $font-size-small;
            @include transition(all);
          }

          .count {
            font-size: $font-size-small;
            color: $text-secondary;
            background: $bg-light;
            padding: 1px 6px;
            border-radius: $radius-round;
            @include transition(all);
          }

          &:hover {
            background: rgba($color-primary, 0.08);

            .el-icon,
            .label {
              color: $color-primary;
            }

            .count {
              background: rgba($color-primary, 0.1);
              color: $color-primary;
            }
          }

          &.is-active {
            background: rgba($color-primary, 0.1);

            .el-icon,
            .label {
              color: $color-primary;
              font-weight: 500;
            }

            .count {
              background: $color-primary;
              color: white;
            }
          }
        }
      }
    }
  }

  /**
   * 分组区域
   */
  .group-section {
    .group-list {
      display: flex;
      flex-direction: column;
      gap: 4px;

      /**
       * 分组项
       */
      .group-item {
        padding: 8px 12px;
        border-radius: $radius-medium;
        cursor: pointer;
        @include transition(all);
        display: flex;
        justify-content: space-between;

        .group-info {
          display: flex;
          align-items: center;
          gap: 8px;
          flex: 1;
          overflow: hidden;
          max-width: calc(100% - 60px); /* 确保留出空间给计数器 */

          .el-icon {
            flex-shrink: 0;
            font-size: 16px;
            @include transition(all);
          }

          .name {
            font-size: $font-size-small;
            @include transition(all);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .info-icon {
            flex-shrink: 0;
            color: $text-secondary;
            font-size: 14px;
            margin-left: -4px;
          }
        }

        .group-actions {
          display: flex;
          align-items: center;
          flex-shrink: 0;
          width: 60px; /* 固定宽度 */
          justify-content: flex-end;
          position: relative;

          .count {
            min-width: 30px;
            text-align: center;
            font-size: $font-size-small;
            color: $text-secondary;
            background: $bg-light;
            padding: 1px 6px;
            border-radius: $radius-round;
            @include transition(all);
          }

          .edit-icon {
            position: absolute;
            right: 0;
            font-size: 14px;
            color: $text-secondary;
            opacity: 0;
            @include transition(all);

            &:hover {
              color: $color-primary;
            }
          }
        }

        &:hover {
          background: rgba($color-primary, 0.08);

          .el-icon,
          .name {
            color: $color-primary;
          }

          .group-actions {
            .count {
              opacity: 0;
            }

            .edit-icon {
              opacity: 1;
            }
          }
        }

        &.is-active {
          background: rgba($color-primary, 0.1);

          .el-icon,
          .name {
            color: $color-primary;
            font-weight: 500;
          }

          .group-actions {
            .count {
              background: $color-primary;
              color: white;
            }
          }
        }
      }
    }
  }
}

// 添加tooltip样式
:deep(.el-tooltip__popper) {
  max-width: 240px;
  line-height: 1.5;
  font-size: $font-size-small;
  padding: 10px 12px;
}
</style>
